package main.java.com.lee.thread;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2021/12/8
 */
public class GraceShutDownThreadPool {

	public static void main(String[] args) throws InterruptedException {
		graceShutdown();
	}

	private static void graceShutdown() throws InterruptedException {
		ExecutorService executor = Executors.newFixedThreadPool(3);
		IntStream.rangeClosed(1, 10).forEach(i->{
			executor.submit(() -> {
				System.out.println(i);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
		});

//		System.out.println("线程池开始关闭"+ LocalDateTime.now());
		executor.shutdown();
//		executor.shutdownNow();
//		executor.awaitTermination(10, TimeUnit.SECONDS);
//		System.out.println("线程池关闭成功"+ LocalDateTime.now());

		if(!executor.isTerminated()) {
			try  {
				for (int i = 0; i < 1000; i++) {//循环关闭1000次，每次等待10毫秒
					System.out.println("第: " + i + "次关闭");
					if (executor.awaitTermination(10, TimeUnit.MILLISECONDS)) {
						break;
					}
					executor.shutdown();
				}} catch (InterruptedException e)  {
				System.err.println(e.getMessage());
			} catch (Throwable e)  {
				System.err.println(e.getMessage());
			}
		}
	}
}
